package com.lbiuse.wx;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.lbiuse.wx.bean.AccessToken;
import com.lbiuse.wx.bean.JSAPITicket;
import org.apache.log4j.Logger;

public class DefaultWechatCache implements WechatCache {
	private static Logger logger= Logger.getLogger(DefaultWechatCache.class);
	private static final Map<String, JSAPITicket> JSAPITICKET_CACHE = new HashMap<String, JSAPITicket>();
	private static final Map<String, AccessToken> ACCESSTOKEN_CACHE = new HashMap<String, AccessToken>();
	public static int ACCESSTOKEN_CACHE_TIME = 6000;
	public static int JSAPITICKET_CACHE_TIME = 6000;

	@Override
	public AccessToken getAccessToken(String appId) {
		AccessToken token = ACCESSTOKEN_CACHE.get(appId);
		if (token == null)
			return null;
		Long now = System.currentTimeMillis();
		Long old = token.getCreateTime();
		if (now - old > ACCESSTOKEN_CACHE_TIME * 1000) {
			logger.info(appId+"微信accessToken缓存失效");
			return null;
		}
		if(logger.isDebugEnabled()){
			Date nowTime = new Date();
			Date  cacheTiem= new Date(old);

		logger.debug(appId+"微信accessToken缓存获取成功，获取时间："+nowTime+"缓存时间："+cacheTiem+"时间间隔："+(now-old)+"毫秒");
		}

		return token;
	}

	@Override
	public void cacheAccessToken(String appId, AccessToken accessToken) {
		ACCESSTOKEN_CACHE.put(appId, accessToken);
	}

	@Override
	public JSAPITicket getJSAPITicket(String appId) {
		JSAPITicket ticket = JSAPITICKET_CACHE.get(appId);
		if (ticket == null)
			return null;
		Long now = System.currentTimeMillis();
		Long old = ticket.getCreateTime();
		if (now - old > JSAPITICKET_CACHE_TIME * 1000) {
			return null;
		}
		return ticket;
	}

	@Override
	public void cacheJSAPITicket(String appId, JSAPITicket ticket) {
		JSAPITICKET_CACHE.put(appId, ticket);
	}

}
